<template>
  <div class="dc-page-design-l-l">
    <el-tree :data="drawingListForTree"
             :props="treeProps"
             draggable
             default-expand-all
             :allow-drop="allowDrop"
             @node-click="drawTreeNodeClick"
             @node-drop="handlerDrawTreeDrop"
    >
      <template #default="{ data }">
        <div>
          <svg-icon :icon-class="data.org.__config__.tagIcon" />
          {{ data.title }}
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  activeData: Object
})

const emit = defineEmits(['active-comp'])

// 从 mixin 中获取注入的属性
const drawingList = ref([])

const treeProps = {
  children: 'list',
  label: 'title'
}

// 为左边布局页签处理数据
const drawingListForTree = computed(() => {
  return setDrawTree(drawingList.value)
})

// 激活组件
const activeComp = (config) => {
  emit('active-comp', config)
}

// 绘制树的点击事件
const drawTreeNodeClick = (data) => {
  activeComp(data.org)
}

const handlerDrawTreeDrop = (draggingNode, dropNode, dropType) => {
  console.log('tree drop: ', draggingNode, dropNode, dropType)
}

// 处理绘制列表为树状结构
const setDrawTree = (list) => {
  const treeData = []
  for (let i = 0; i < list.length; i++) {
    const drawingItem = list[i]
    const item = {
      title: drawingItem.__config__.compName || drawingItem.__config__.label || drawingItem.label,
      org: drawingItem,
      list: []
    }
    if (drawingItem.__config__.children) {
      item.list = setDrawTree(drawingItem.__config__.children)
    }
    treeData.push(item)
  }
  return treeData
}

const allowDrop = (draggingNode, dropNode, type) => {
  // 拖拽时判定目标节点能否被放置。
  // draggingNode:拖动节点 dropNode:目标节点
  // type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
  if (type !== 'inner') {
    return true
  }
  const target = dropNode.data
  if (!target) {
    return true
  }
  return Array.isArray(target.org?.__config__?.children)
}
</script>

<style lang='scss' scoped>
.components-title {
  display: flex;
  align-items: center;

  .svg-icon {
    margin-right: 6px;
    font-size: 16px;
  }
}
</style>
